# -*- coding:utf-8 -*-
# @Time: 2020-08-29 17:59
# @Author: aniu
# @File: jwtAuth.py

# -*- coding:utf-8 -*-
# @Time: 2020-08-14 16:30
# @Author: aniu
# @File: jwt_auth.py

'''
    生成jwt
'''
import datetime

from application import app
from web.common.jsonUtil import parseData
import jwt
JWT = app.config.get('SECRET_KEY')

def create_token(payload, timeout=20):
    """
        :param payload {'userid'：1, 'usernaem':''}用户信息
        :param timeout: token过期时间，默认20分钟
    """
    try:

        headers = {
            'typ':'jwt',
            'alg':'HS256'
        }
        payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
        result = jwt.encode(payload=payload, key=JWT, algorithm='HS256', headers=headers).decode()
        return result
    except Exception as e:
        return parseData(400,e,'token创建错误')




def parse_payload(token):
    '''
        对token进行发型校验并获取payload
    '''
    try:
        verified_payload = jwt.decode(token, JWT, True)
        return parseData(200, verified_payload, 'token认证成功')
    except jwt.ExpiredSignatureError:
        return  parseData(500, '','token已失效')
    except jwt.DecodeError:
        return parseData(404, '','token认证失败')
    except jwt.InvalidTokenError:
        return parseData(400, '','非法token')